<template>
  <view class="sale_body flex "  :style="{height:screenHeight+'px'}">
    <view class="sale_title">
      <view class="flex a-item j-center back" @click="back">
        <img src="static/image/goBack.png">
      </view>
      <!--			<search-input  placeholder="请输入关键字搜索" />-->
      <view class="pageTile flex a-item j-center">
        {{ getTitle(type)   }}
      </view>
      <view class="add_goods flex a-item" @tap="jumpAddGoods">
        <img src="static/image/add.png" />
        &nbsp添加
      </view>
    </view>
    <view class="fl1 oat">
      <view class="sale_content" @click.self="close">
          <view class="flex align-c search_box">
            <view>
              <image class="search_img" src="/static/image/search2.png" alt="" />
            </view>
            <picker class="flex align-c downs" style="width: 150rpx;" mode='selector' range-key="name" :range="warelist"  @change="changeware($event,'warehouse','warelist')" >
              <view>{{order.warehouseName||'请选择一个仓库' }}</view>
            </picker>
          </view>
          <!-- </view> -->
        <view class="order_list">
          <order-goods ref="og" @del="delGoods(item)" :item="item" v-for="item in selectGoodsList" :type='type'/>
        </view>
        <view class="total_box flex" >
          <view class="fl1 label">
            总箱数:{{ totalBox }}
          </view>
          <view class="fl1 label">
            总金额:{{totalAmount}}
          </view>
        </view>
        <view class="total_box flex"  v-if="type === 'cart' || type === 'pass' || type === 'updateSale'">
          <view class="label">
            配送时间:
          </view>
          <picker class="label flex a-item" mode="date" :value="form.sendDate" @change="sendDateChange">
            <view style="color: #BEC6D2;">{{ form.sendDate || '请选择开始日期' }}</view>
          </picker>
        </view>
        <textarea class="remark total_box" placeholder="备注"  maxlength=50 style="height: 235rpx"  v-model="form.remark" />
        <notify-user :notify-user-ids.sync="form.notifyUserIds" :notify-user-name="form.notifyUserName"  v-if="type === 'cart' || type === 'updateSale'"  :isEdit="!form.id"/>
        <ratify-user v-if="taskApprove.id" :taskApprove="taskApprove" />
        <ratifying v-if="taskApprove.id" :taskApprove="taskApprove" style="background: white"/>
        <view style="height:100rpx;background: white"/>
      </view>
      <view v-if="!taskApprove.currentNodeNo" class="bottom_submit">
        <view class="submit" @tap="save()">提交</view>
      </view>
    </view>

  </view>
</template>

<script>
import pageMixin from "../../mixins/pageMixin";
import searchInput from "../../components/searchInput.vue";
import {removeCacheShoppingCart, ShoppingCartList} from "../../models/shoppingCart";
import {
  getAppSalesOrder,
  saveAppSalesOrder,
  saveSalesOrder, saveWareReturnBottleBox,
  wareReturnBottleBoxDetail
} from "../../request/api/sales";
import orderGoods from "@/components/orderGoods.vue";
import {
  addCustomerStock,
  submit,
  basWarehouseList,
  basCustomerList, wareReturnBottleBox
} from "../../request/api/customer_visit";
import {getDict, getSaleType} from '../../request/api/common_down'
import searchselect from "@/components/searchselect.vue";
import {appBack, jumpAppPage} from "../../common/android_interfacce";
import CustomerInfo from "../../components/customerInfo.vue";
import {curDate, setImage} from "../../common/auth";
import pub from "../../common/pub";
import proxyGoods from "../../models/proxyGoods";
import ratifying from "../../components/ratifying.vue";
import ratifyUser from "../../components/ratifyUser.vue";
import NotifyUser from "../../components/notifyUser.vue";
import {getWareOtherEnter, saveWareOtherEnter, wareOtherEnterDetail} from "@/request/api/inventory";

export default {
  name: "shopping",
  mixins: [pageMixin],
  components: {
    NotifyUser,
    ratifyUser,
    ratifying,
    CustomerInfo,
    searchInput,
    orderGoods
  },
  data() {
    return {
      keyword: '',
      selectGoodsList:[],
      customer:{},
      form:{
        //1销售2退货
        type:1,
        saleType:1,
        busDate:curDate(),
        sendDate:'',
        remark:'',
        notifyUserIds:'',
        notifyUserCode:"",
        notifyUserName:''

      },
      orderForm:['现金','月结','代铺','年结'],
      type:'otherEnter',
      saveType:{
        cart:saveSalesOrder,
        stock:addCustomerStock,
        buy:submit,
        capCart:wareReturnBottleBox,
        updateSale:saveAppSalesOrder,
        pass:saveAppSalesOrder,
        capCartOrder:saveWareReturnBottleBox
      },
      taskApprove:{},
      warelist:[],
      channellist:[],
      scrollend:false,
      customerlist:[],
      page1:1,
      size1:20,
      totalAmount:0,
      totalBox:0,
      val:'',
      buyChannel:'',
      Channel:'',
      warehouseName:'',
      customerInfo:{},
      saleTypeList:[],
      order:{}
    }
  },
  created() {
    this.getware()
    pub.$on('updateGoodsData',()=>{
      this.refresh()
    })
  },
  destroyed(){
    pub.$remove('updateGoodsData')
  },
  onLoad(option){
    this.selectGoodsList = new ShoppingCartList(this.type).toList()
    if (option.id === 'ADD'){
      this.order =  {
        warehouseId: null,
        warehouseName: null,
        userId: null,
        deptId: null,
        type: 1,
        remark: this.form.remark,
        detailList: this.selectGoodsList
      }
    }else{
      wareOtherEnterDetail({orderId: option.id}).then(res => {
        this.order = res.data.order;
        this.selectGoodsList.push(...res.data.content.map(item => proxyGoods(item)))
      })
    }
  },
  methods: {
    close() {
    },
    changeType(e) {
      this.form.type = Number.parseInt(document.querySelector('#order_type').value)
    },
    sendDateChange(e) {
      this.form.sendDate = e.detail.value
    },
    refresh() {
      this.totalAmount = this.selectGoodsList.reduce((sum, item) => {
        return item.taxAmount + sum
      }, 0)
      const list = this.selectGoodsList.reduce((sum, item) => {
        sum[0] += item.boxNum;
        sum[1] += item.mainNum;
        return sum
      }, [0, 0])
      this.totalBox = `${list[0]}箱${list[1]}瓶`
    },
    // 仓库
    getware() {
      basWarehouseList({size: 999}).then(res => {
        this.warelist = res.content
      })
    },
    //获取销售类型
    async getSaleTypeDict(){
      const res = 	await getSaleType()
      this.saleTypeList = res.data.content
    },

    selectDealer() {
      pub.$on('selectCustomer', (e) => {
        this.form.deliveryProviderId = e.id
        this.form.deliveryProviderName = e.name
        this.$forceUpdate();
      })
      uni.navigateTo({
        url: `/pages/customer/index?params=${JSON.stringify({isDealer: 1})}`
      })
    },
    selectCustomer() {
      pub.$on('selectCustomer', (e) => {
        this.form.customerId = e.id
        this.form.customerName = e.name
        this.customer = JSON.stringify({
          customerId:e.id,
          customerName:e.name,
          type:this.type
        })
        this.$forceUpdate();
      })
      uni.navigateTo({
        url: `/pages/customer/index?params=${JSON.stringify({isContact: 1})}`
      })
    },
    changeware(val, assignment, list) {
      let index = val.detail.value >> 0
      this.order[assignment + 'Id'] = this[list][index].id
      this.order[assignment + 'Name'] = this[list][index].name
    },
    queryData() {
      if (this.scrollend) return
      this.page1++
      // 调取数据
      this.customers(this.val)
    },
    init() {
      this.customerlist = []
      this.page1 = 1
    },
    getfocus() {
      if (!this.val) {
        this.init()
        this.customers()
      }
    },
    touchout() {
      if (this.val) {
        this.page1++
        this.customers(this.val)
      } else {
        this.page1++
        this.customers(this.val)
      }

    },
    rowclick(val) {
      this.customer = {}
      this.customer.customerName = val.name
      this.customer.customerId = val.id
      this.customer.type = this.type
      this.form.visitedCustomerId = val.id
      this.customer = JSON.stringify(this.customer)
      this.$refs.content.editContent(val.name)
    },
    unname() {
      this.customer = {}
      this.$refs.content.editContent()
    },
    searchOrderDetail(e) {

    },
    delGoods(goods) {
      //如果是促销则删除所有促销明细
      if (goods.promotionGroupKey) {
        const pml = this.selectGoodsList.filter(item => item.promotionGroupKey === goods.promotionGroupKey)
        for (let i in pml) {
          const index = this.selectGoodsList.findIndex(item => item === pml[i])
          if (~index) {
            this.selectGoodsList.splice(index, 1)
          }
        }
        return;
      }
      const index = this.selectGoodsList.findIndex(item => item === goods)
      if (~index) {
        this.selectGoodsList.splice(index, 1)
      }
      this.refresh()
    },
    touchstart(e) {
      const touch = e.touches[0] || e.changedTouches[0]
      this.x = touch.clientX
    },
    touchmove(e) {
      if (!this.updateNum) return
      const touch = e.touches[0] || e.changedTouches[0]
      const marginLeft = (touch.clientX - this.x) >> 0
      if (this.left) {
        if (marginLeft < 0) {
          this.marginLeft = -150
        } else if (marginLeft > 160) {
          this.marginLeft = 10
        } else {
          this.marginLeft = -150 + marginLeft
        }
      } else {
        if (marginLeft < -150) {
          this.marginLeft = -150
        } else if (marginLeft > 10) {
          this.marginLeft = 10
        } else {
          this.marginLeft = marginLeft
        }
      }

    },
    touchend(e) {
      if (this.marginLeft < -75) {
        this.marginLeft = -150
        this.left = true
      } else {
        this.marginLeft = 10
        this.left = false
      }
    },
    back() {
        history.back()
    },

    jumpAddGoods() {
      //审核不允许添加
      this.isPass()
      //回瓶回箱路径修改
        uni.navigateTo(
            {url: `/pages/shopping/index?params=${ JSON.stringify({type:"BUY"}) }&type=${this.type}`,}
        )
      // uni.$emit('curCustomer',{customerId:1,customerName:'老王'})
    },
    isPass() {
      if (this.type === 'pass') {
        uni.showToast({
          icon: 'none',
          title: '审核状态不允许修改',
        })
        throw Error('审核状态不允许修改')
      }
    },
    getTitle(type){
      // cart，updateSale:销售单,stock: 回瓶回箱,buy: 采购单,
      return "其他入库"
    },
    async save() {
      if ( !this.order.warehouseId) {
        uni.showToast({title: '请先选择仓库', icon: 'none'})
        return
      }
      uni.showLoading({title: '保存中'})
      try {
          this.order.detailList = this.selectGoodsList
        const res = await saveWareOtherEnter(this.order)

        uni.hideLoading()
        if (res.status === 200) {
          uni.showToast({title: '保存成功', icon: 'none'})
          removeCacheShoppingCart(this.type)
          history.back()
          //uni.navigateBack()
        } else {
          uni.showToast({title: res.msg, icon: 'none'})
        }
      } catch (e) {
        uni.hideLoading()
      }
    }
  }
}
</script>
<style scoped lang="scss">
.sale_body {
  width: 100%;
  flex-direction: column;

  .sale_title {
    background: white;
    display: flex;
    height: 186 rpx !important;
    padding-top: 88rpx;
    padding-bottom: 20rpx;

    .back {
      width: 50rpx;
      height: 66rpx;

      img {
        width: 40rpx;
        height: 40rpx;
      }
    }

    .add_goods {
      font-weight: bold;
      color: #016EF9;
      line-height: 30rpx;
      width: 120rpx;
      margin-left: 40rpx;

      img {
        width: 27rpx;
        height: 27rpx;
      }
    }
  }

  .sale_content {
    padding: 1%;
    position: relative;
    z-index: 19;
    .type {
      height: 90rpx;

      .bill {
        width: 130rpx;
        height: 50rpx;
        font-size: 36rpx;
        font-weight: bold;
        text-align: center;
        color: #999999;

        margin: 1%;
      }

      .select_bill {
        height: 50rpx;
        color: #333333;

        &:after {
          content: '';
          display: block;
          width: 33rpx;
          height: 7rpx;
          background: #016EF9;
          margin: auto;
          margin-top: 10rpx;
        }
      }

      .sale_type {
        width: 140rpx;
        height: 52rpx;
        color: #016EF9;
        font-size: 28rpx;
        font-weight: bold;
        border-radius: 7rpx;
        margin-right: 20rpx;
        background: rgba(1, 110, 249, 0.10);
      }
    }
  }
  .search_box{
    width: 90%;
    margin: 0 auto;
    border: 1px solid #d1d6de;
    display: flex;
    height: 60rpx;
    border-radius: 10rpx;
    align-items: center;
    padding: 5rpx;
    .search_img{
      width: 40rpx;
      height: 40rpx;
    }
    .downs{
      flex:1;
    }
  }
  .bottom_submit {
    background: white;
    height: 100rpx;
    width: 100%;
    font-size: 32rpx;
    font-weight: 600;
    display: flex;
    justify-content: center;
    padding-top: 15rpx;
    position: fixed;
    bottom: 0;
    z-index: 20;
    .text_button {
      width: 180rpx;
      height: 100%;
      display: flex;
      align-items: center;

      img {
        width: 35.46rpx;
        height: 35.46rpx;
      }
    }
    .submit {
      width: 700rpx;
      height: 60rpx;
      border-radius: 10rpx;
      background: #016EF9;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
    }
  }
}
.pageTile{
  width: 80%;
  font-size: 36rpx;
  font-weight: 500;
  color: #333333;
}
.customer_info_box,.sales_info_box{
  background: white;
  margin: 10rpx;
  padding: 10rpx 20rpx;
  .info{
    color: #909090;
    font-size: 25rpx;
  }
}
.order_type_box{
  background: white;
  margin: 10rpx;
  padding: 20rpx;
  color: #909090;
  font-size: 25rpx;
  select{
    border: none;
    font-size: 30rpx;
    color: blue;
    background: white;
  }

}
.oat{
  overflow-y: auto;
}
.total_box{
  padding: 25rpx;
  width: 680rpx;
  margin-bottom: 5rpx;
  background: white;
  .label{
    color: #666666;
    font-size: 26rpx;
  }
  img{
    width: 30rpx;
    height: 30rpx;
  }
}
.remark {
  color: #016EF9;
  font-weight: bold;
  font-size: 28rpx;
  height: 100%;
  background: white;
  img {
    width: 27rpx;
    height: 32rpx;
  }
}
select{
  color:red !important;
  font-size: 25rpx !important;
}
</style>
